//
//  NoteDetailViewController.m
//  eBook
//
//  Created by zhy on 12-12-3.
//  Copyright (c) 2012年 zhan. All rights reserved.
//

#import "NoteDetailViewController.h"
#import "AppDelegate.h"
@interface NoteDetailViewController ()

@end

@implementation NoteDetailViewController

#pragma mark - lifecycle
@synthesize noteTableView;
//@synthesize noteTitle;
@synthesize noteContent;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_bg.png"]];
    UIView *leftView = [self.view viewWithTag:1];
    leftView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_left.png"]];
    UIView *rightView = [self.view viewWithTag:2];
    rightView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_right.png"]];
    
    UIControl *KBcontrol = [[UIControl alloc] initWithFrame:CGRectMake(0, 20, 1024, 748)];
    [KBcontrol addTarget:self action:@selector(backgroudTap) forControlEvents:UIControlEventTouchDown];
    [rightView addSubview:KBcontrol];
    [rightView sendSubviewToBack:KBcontrol];
    
    noteTableView.backgroundColor = [UIColor clearColor];
    noteTableView.delegate = self;
    noteTableView.dataSource = self;
    
    noteArray = [[NSMutableArray alloc] init];
    flagArray = [[NSMutableArray alloc] init];
    
//    currentTitle = [[NSString alloc] init];
    currentContent = [[NSString alloc] init];
    
//    noteTitle.backgroundColor = [UIColor clearColor];
    noteContent.backgroundColor = [UIColor clearColor];
    
    [self loadArrayFromCoredata];
    
    if ([noteArray count] !=0) {
//        noteTitle.text = [[noteArray objectAtIndex:0] valueForKey:@"title"];
        noteContent.text = [[noteArray objectAtIndex:0] valueForKey:@"content"];
        
//        currentTitle = noteTitle.text;
        currentContent = noteContent.text;
        currentRow = 0;
        
        NSIndexPath *first=[NSIndexPath indexPathForRow:0 inSection:0];
        [noteTableView selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionBottom];
    } else{
        currentRow = -1;
    }

}

- (void)viewDidUnload
{
    [self setNoteTableView:nil];
//    [self setNoteTitle:nil];
    [self setNoteContent:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft||interfaceOrientation==UIInterfaceOrientationLandscapeRight);
}

//ios 6 rotation
-(NSUInteger)supportedInterfaceOrientations{
//    return UIInterfaceOrientationLandscapeLeft;//xcode 4.4
    return UIInterfaceOrientationMaskLandscape;//xcode 4.5
}

- (BOOL)shouldAutorotate
{
    return YES;
}

#pragma mark -Private Method
-(void) loadArrayFromCoredata{
    
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Note"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    
    if (objects == nil) {
        NSLog(@"there was a error!");
    }
    
    [noteArray removeAllObjects];
    [flagArray removeAllObjects];
    
    if ([objects count] != 0) {
        
        for (NSManagedObject *oneObject in objects) {
            
            NSNumber *chapter = [oneObject valueForKey:@"chapter"];
//            NSString *title = [oneObject valueForKey:@"title"];
            NSString *content = [oneObject valueForKey:@"content"];
            
            NSDictionary *onedata = [[NSDictionary alloc] initWithObjectsAndKeys:chapter,@"chapter",content,@"content",nil];
            
            [noteArray addObject:onedata];
            [flagArray addObject:@"0"];
        }
    }

    NSLog(@"aaaaaaaaaaaaa%d",[noteArray count]);
}

-(void) deleteDatafCoreDatawithIndex:(int) index{
    
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Note"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    [context deleteObject:[objects objectAtIndex:index]];
    [appDelegate saveContext];
}

-(void) TitleORContentChanged{
    
    //判断是否有修改，有则做标记
    if (currentRow != -1) {
        
        if (![noteContent.text isEqualToString:currentContent]) {
            
            NSNumber *chapter = [[noteArray objectAtIndex:currentRow] valueForKey:@"chapter"];
//            NSString *title = noteTitle.text;
            NSString *content = noteContent.text;
            
            NSDictionary *onedata = [[NSDictionary alloc] initWithObjectsAndKeys:chapter,@"chapter",content,@"content",nil];
            
            NSLog(@"change current row %d",currentRow);
            [noteArray replaceObjectAtIndex:currentRow withObject:onedata];
            [flagArray replaceObjectAtIndex:currentRow withObject:@"1"];
            
        }
    }
}

-(void) backgroudTap{
    [noteContent resignFirstResponder];
}

#pragma mark - tableView Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [noteArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"noteTableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    UIView *selectedView = [[UIView alloc] initWithFrame:cell.contentView.frame];
    selectedView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"menu_cell.png"]];
    cell.selectedBackgroundView = selectedView;
    
    NSLog(@"select frame %f, %f ",selectedView.frame.size.height,selectedView.frame.size.width);
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:1];
    UILabel *chapterLabel = (UILabel *)[cell viewWithTag:2];
    
    NSString *title = [[noteArray objectAtIndex:indexPath.row] valueForKey:@"content"]; // fix：title- > content
    int chapter = [[[noteArray objectAtIndex:indexPath.row] valueForKey:@"chapter"] intValue];
    
    titleLabel.text = title;
    chapterLabel.text = [NSString stringWithFormat:@"第%d章",chapter];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"row is %d",indexPath.row);
    
    [noteContent resignFirstResponder];
    
    //判断是否有修改，有则做标记
    [self TitleORContentChanged];

//    noteTitle.text = [[noteArray objectAtIndex:indexPath.row] valueForKey:@"title"];;
    noteContent.text = [[noteArray objectAtIndex:indexPath.row] valueForKey:@"content"];
    
//    currentTitle = noteTitle.text;
    currentContent = noteContent.text;
    currentRow = indexPath.row;
}

-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [noteArray removeObjectAtIndex:indexPath.row];
        [flagArray removeObjectAtIndex:indexPath.row];
        [self deleteDatafCoreDatawithIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        currentRow = -1;
        
        if ([noteArray count] !=0) {
//            noteTitle.text = @"";
            noteContent.text = @"";
        
        } else{
//            noteTitle.text = @"";
            noteContent.text = @"当前没有笔记！";
        }
        
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - Action 
- (IBAction)doneAction:(id)sender {
    
    if (currentRow != -1) {
        
        [self TitleORContentChanged];
        
        for (NSString * f in flagArray) {
            NSLog(@"    %@",f);
        }
        
        //data change so core data should change
        
        //保存进core data
        AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = appDelegate.managedObjectContext;
        NSEntityDescription *entityDescription = [NSEntityDescription
                                                  entityForName:@"Note"
                                                  inManagedObjectContext:context];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entityDescription];
        NSError *error;
        NSArray *objects = [context executeFetchRequest:request error:&error];
        if (objects == nil) {
            NSLog(@"core data have not object,there was a error!");
        }
        
        
        for ( int i = 0;i<[flagArray count] ;i++) {
            
            NSString * f = [flagArray objectAtIndex:i];
            
            if ([f isEqualToString:@"1"]) {
                
                NSManagedObject * oneObject = [objects objectAtIndex:i];
                
                [oneObject setValue:[[noteArray objectAtIndex:i] valueForKey:@"chapter"]forKey:@"chapter"];
//                [oneObject setValue:[[noteArray objectAtIndex:i] valueForKey:@"title"] forKey:@"title"];
                [oneObject setValue:[[noteArray objectAtIndex:i] valueForKey:@"content"] forKey:@"content"];
                
                NSLog(@"core data change at %d",i);
            }
            
        }
        
        [appDelegate saveContext];
     
    }
    
    [self dismissViewControllerAnimated:YES completion:^{}];
    
}

@end
